<template>
    <div>
        <!-- 搜索 -->
        <el-row :gutter="10" style="margin-bottom: 10px">
            <el-col :span="4">
                <el-input
                    v-model="product.name"
                    placeholder="用户名"
                    clearable
                ></el-input>
            </el-col>
            <el-col :span="4">
                <el-input
                    v-model="product.startPrice"
                    placeholder="最低消费金额"
                    clearable
                ></el-input>
            </el-col>
            <el-col :span="4">
                <el-input
                    v-model="product.endPrice"
                    placeholder="最高消费金额"
                    clearable
                ></el-input>
            </el-col>

            <el-col :span="4">
                <el-button type="warning" @click="bindSearch"
                    >搜索用户</el-button
                >
            </el-col>
        </el-row>
        <!-- 表格 -->
        <el-table
            :data="goodsList"
            style="width: 100%"
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="55" />
            <el-table-column
                label="序列号"
                prop="id"
                width="80"
            ></el-table-column>
            <el-table-column label="图片">
                <template #default="scope">
                    <el-image
                        :src="
                            'http://localhost:3000/test/pic?img=' +
                            scope.row.img_url
                        "
                        style="width: 60px; height: 60px"
                    ></el-image>
                </template>
            </el-table-column>
            <el-table-column
                label="用户名"
                prop="userName"
                width="180"
            ></el-table-column>
            <el-table-column label="昵称" prop="nick"></el-table-column>
            <el-table-column label="会员等级" prop="level"></el-table-column>
            <el-table-column label="订单总数">
                <template #default="scope">
                    共{{ scope.row.num }}单
                    <!-- {{ arr2[0] }} -->
                    <!-- {{ getUserOderList(scope.row.userName,1) }} -->
                    <!-- {{ testFn() }} -->
                </template>
            </el-table-column>
            <el-table-column label="总消费金额">
                <template #default="scope">
                    ￥{{ scope.row.total_price }}
                    <!-- {{ arr3[0] }} -->
                    <!-- {{ getUserOderList(scope.row.userName,2) }} -->
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <div class="btnBox">
                        <el-button
                            type="success"
                            size="small"
                            @click="bindEdit(scope.row)"
                            >详情</el-button
                        >

                        <el-popconfirm
                            title="确认要删除此记录吗?"
                            @confirm="bindDelete(scope.row.id)"
                        >
                            <template #reference>
                                <el-button type="danger" size="small"
                                    >删除</el-button
                                >
                            </template>
                        </el-popconfirm>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
            background
            layout="total,sizes,prev, pager, next, jumper"
            :total="total"
            :default-page-size="10"
            :page-sizes="[5, 10, 20, 30]"
            @size-change="bindSizeChange"
            @current-change="bindCurrentChange"
        ></el-pagination>
    </div>
</template>

<script lang="ts">
import // RequestShopList,
// RequestDeleteGoods,
// RequestBatchDelete,
'@/api/index'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { excelExport2 } from '@/utils/xlsxutil'
import { baseURL } from '@/utils/request'
export default {
    data() {
        return {
            goodsList: [],
            dialogGoodsFormVisible: false,
            total: 0, // 总记录条数
            pageSize: 10, // 每页记录条数
            pageNo: 1, // 当前页号
            type: 'ADD', // EDIT 编辑 ADD 添加
            goods: null,
            product: {
                name: '', // 搜索产品名称
                price: '', //搜索产品价格
                shop: '', // 店铺名称
                startPrice: '', //开始价格
                endPrice: '', //结束价格
            },
            ids: '', // 删除商品id 集合
            arr2: [],
            arr3: [],
        }
    },
    created() {
        this.getShopList()
        this.getUserOderList()
    },
    methods: {
        filterUrl(url) {
            return url?.indexOf('http') === -1 ? baseURL + url : url
        },
        // testFn(arr2){
        //     return arr2
        // },
        /**
         * 用户列表
         */
        async getShopList() {
            const data = await axios({
                method: 'get',
                url: 'http://localhost:3000/users/list',
                //post请求参数使用data选项, get参数 params选项
                params: {
                    pageNum: this.pageNo,
                    pageSize: this.pageSize,
                    name: this.product.name,
                    shop: this.product.shop,
                    // startPrice: this.product.startPrice,
                    // endPrice: this.product.endPrice,
                },
            })
            const { code, info } = data.data
            if (code === 1) {
                this.total = info.total // 总记录条数
                this.goodsList = info.list
                // this.goodsList.forEach(item,index=>{
                //     return {...item}
                // })

                this.getUserOderList()
            } else {
                this.total = 0
                this.goodsList = []
            }
        },

        /**
         * 获取对应用户的订单列表
         */
        async getUserOderList() {
            const data = await axios({
                method: 'get',
                url: 'http://localhost:3000/goods/orderlist',
                //post请求参数使用data选项, get参数 params选项
                params: {
                    pageSize: 100,
                },
            })
            const { code, info } = data.data
            if (code === 1) {
                // console.log('info.list>>>',info.list)
                info.list.map(item => {
                    item.num = 1
                    return item
                })


                let newArray = info.list.reduce((total:any, cur:any, index:any) => {
                    let hasValue = total.findIndex(current => {
                        return current.user === cur.user
                    })
                    hasValue === -1 && total.push(cur)
                    hasValue !== -1 &&
                        (total[hasValue].total_price =
                            total[hasValue].total_price + cur.total_price)
                    hasValue !== -1 &&
                        (total[hasValue].num = total[hasValue].num + cur.num)
                    return total
                }, [])
                // console.log('newArray>>>',newArray)
                // console.log('goodsList>>>',this.goodsList)
                this.goodsList = this.goodsList.map((item, index) => {
                    return {
                        ...item,
                        total_price: newArray[index].total_price,
                        num: newArray[index].num,
                    }
                })
                // console.log('reslut>>>',this.goodsList)
                if (this.product.startPrice) {
                    this.goodsList = this.goodsList.filter(item=>item.total_price>this.product.startPrice)
                }
                if (this.product.endPrice) {
                    this.goodsList = this.goodsList.filter(item=>item.total_price<this.product.endPrice)
                }
                // console.log('this.goodsList',this.goodsList)

                // let arr2 = []
                // let arr3 = []
                // newArray.map(item => {
                //     arr2.push(item.total_price)
                //     arr3.push(item.num)
                // })
                // // this.testFn(arr2[0])
                // if(id===2) console.log(arr2)
                // if(id===1) console.log(arr3)
            } else {
                console.log(1)
            }
        },
        /**
         * 查看订单
         */
        bindEdit(row) {
            console.log(row.id)
            this.$router.push({ path: '/orderDetail', query: { id: row.id } })
        },
        /**
         * 删除商品
         */
        async bindDelete(id) {
            const data = await axios({
                method: 'post',
                url: 'http://localhost:3000/goods/deleteorder',
                //post请求参数使用data选项, get参数 params选项
                data: {
                    id,
                },
            })
            const { code } = data.data
            if (code === 1) {
                this.getShopList()
                ElMessage({
                    type: 'success',
                    message: '删除成功!',
                })
            }
        },
        /**
         * 添加-弹出添加表单对话框
         */
        bindAddGood() {
            this.type = 'ADD'
            this.dialogGoodsFormVisible = true
        },
        /**
         * 刷新
         */
        bindRefresh() {
            this.product = {} // 重置搜索数据
            this.getShopList()
        },
        bindCloseDialog() {
            this.dialogGoodsFormVisible = false
            this.getShopList()
        },
        /**
         * 页大小改变事件
         */
        bindSizeChange(value) {
            this.pageSize = value
            this.getShopList()
        },
        /**
         * 页号改变事件
         */
        bindCurrentChange(value) {
            this.pageNo = value
            this.getShopList()
        },
        /**
         * 搜索产品
         */
        bindSearch() {
            this.pageNo = 1
            this.getShopList()
        },
        /**
         * 多选
         */
        handleSelectionChange(value) {
            // console.log('value ', value) // [{id:10,name:''}] => [10,12,34] => '10,12,34'
            const list = value.map(item => item.id)
            const ids = list.join(',')
            this.ids = ids
        },
        /**
         * 批量删除
         */
        async bindBatchDelete() {
            // if (this.ids?.split(',').length <= 0) {
            if (!this.ids) {
                console.log('no')
                ElMessage({
                    type: 'info',
                    message: '请选择删除产品',
                })
                return
            }
            console.log(this.ids)
            const res = await axios({
                method: 'post',
                url: 'http://localhost:3000/goods/batchdelete',
                //post请求参数使用data选项, get参数 params选项
                data: {
                    id: this.ids,
                },
            })
            const { code } = res.data
            console.log(code)
            if (code === 1) {
                ElMessage({
                    type: 'success',
                    message: '批量删除成功',
                })
                this.getShopList()
            }
        },
        /**
         * 导出excel
         */
        bindExcelExport() {
            excelExport2(
                this.goodsList,
                {
                    id: '序列号',
                    product: '产品名称',
                    shop: '店铺名称',
                    picture: '图片',
                    price: '价格',
                    oldprice: '原价',
                    categoryname: '类型名称',
                },
                '订单列表'
            )
        },
    },
}
</script>

<style lang="scss" scoped>
.btnBox {
    display: flex;
    align-items: center;
    justify-content: center;
}
</style>
